package com.anolesoft.twelvePlan.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.anolesoft.twelvePlan.dto.MesGyInfoToPlanDTO;
import com.anolesoft.twelvePlan.entity.MesPlanXiadaJixingDO;
import com.anolesoft.twelvePlan.mapper.MesGyInfoMapper;
import com.anolesoft.twelvePlan.mapper.MesPlanXiaDaMapper;
import com.anolesoft.twelvePlan.mapper.MesPlanXiadaJixingMapper;
import com.anolesoft.twelvePlan.service.MesPlanXiaDaService;
import com.anolesoft.twelvePlan.vo.MesGyInfoToPlanVO;
import com.anolesoft.yr.util.CommonUtils;
import com.anolesoft.yr.util.PageData;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zyq
 * @date 2022/3/18
 */
@Service
@Slf4j
public class MesPlanXiaDaServiceImpl implements MesPlanXiaDaService {

    @Autowired
    private MesGyInfoMapper mesGyInfoMapper;
    @Autowired
    private MesPlanXiaDaMapper mesPlanXiaDaMapper;
    @Autowired
    private MesPlanXiadaJixingMapper mesPlanXiadaJixingMapper;

    @Override
    public PageData<List<MesGyInfoToPlanDTO>> queryPlan(MesGyInfoToPlanDTO mesGyInfoToPlanDTO, Integer pageNo, Integer pageSize) {
        Page<MesGyInfoToPlanDTO> page = new Page<>(pageNo, pageSize);
        List<MesGyInfoToPlanDTO> mesGyInfoToPlanDTOS;
        //根节点
        List<MesGyInfoToPlanDTO> root = mesGyInfoMapper.queryPlan(mesGyInfoToPlanDTO, page);
        // 取消分页器sql优化 当sql里left join子句的表中没有字段出现在where子句中时left join子句会被整个优化掉，导致分页器总行数total数量异常，默认为true
        page.setOptimizeCountSql(false);
        if (mesGyInfoToPlanDTO.getFactoryId().equals("16") && StrUtil.isEmptyOrUndefined(mesGyInfoToPlanDTO.getPartid())) {
            //16不使用图号作为查询条件时的树状查询
            log.debug("tree");
            MesGyInfoToPlanDTO isQuery = root.get(0);
            Integer length = mesGyInfoMapper.queryPlanTreeCount(mesGyInfoToPlanDTO);
            if (length == null){
                log.error("null");
                return null;
            }
            log.debug("序号最大长度：" + length);
            mesGyInfoToPlanDTO.setLength(length);
            List<MesGyInfoToPlanDTO> leaf = mesGyInfoMapper.queryPlanTree(mesGyInfoToPlanDTO);
            // 处理只有一级时候的异常
            if (length < 10) {
                mesGyInfoToPlanDTOS = root;
                return new PageData<>(((int) page.getTotal()), mesGyInfoToPlanDTOS);
            }
            // 从叶子节点开始计算直至根节点
            while (length > 0) {
                List<MesGyInfoToPlanDTO> father;
                length -= 10;
                final List<MesGyInfoToPlanDTO> son = leaf;
                if (length > 10) {
                    mesGyInfoToPlanDTO.setLength(length);
                    father = mesGyInfoMapper.queryPlanTree(mesGyInfoToPlanDTO);
                } else {
                    father = root;
                    length -= 10;
                }
                father.forEach(plan -> {
                    if (StrUtil.isEmptyOrUndefined(plan.getSerialnumber())) {
                        return;
                    }
                    String fatherNumber = plan.getSerialnumber() + ".";// 父节点序号
                    final int len = fatherNumber.length();
                    // 根据序号获取该节点的子节点
                    List<MesGyInfoToPlanDTO> children = son.stream()
                            .filter(sonPlan -> fatherNumber.equals(sonPlan.getSerialnumber().substring(0, len)))
                            .collect(Collectors.toList());
                    // 如果没有子节点则不进行赋值 用于实现隐藏展开按钮
                    if (null == children || children.size() == 0) {
                        return;
                    }
                    plan.setChildren(children);
                });
                leaf = father;
            }
            mesGyInfoToPlanDTOS = leaf;
        } else {
            // 普通查询与16带图号查询
            log.debug("normal");
            mesGyInfoToPlanDTOS = root;
        }

        return new PageData<>(((int) page.getTotal()), mesGyInfoToPlanDTOS);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String planXiaDa(List<MesGyInfoToPlanVO> mesGyInfoToPlanVOS, String factoryId, String user) {
        String pattern;
        if (factoryId.equals("16")) {
            pattern = "yyyy-MM-dd";
        } else {
            pattern = "yyyy-MM";
        }
        System.out.println(pattern);
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(pattern);
        String flag;
        MesGyInfoToPlanDTO test = BeanUtil.copyProperties(mesGyInfoToPlanVOS.get(0), MesGyInfoToPlanDTO.class);
        if (mesPlanXiaDaMapper.judgeFlag(test) == 0) {
            flag = "";
        } else {
            flag = "新增";
        }
        for (MesGyInfoToPlanVO mesGyInfoToPlanVO : mesGyInfoToPlanVOS) {
            MesGyInfoToPlanDTO mesGyInfoToPlanDTO = BeanUtil.copyProperties(mesGyInfoToPlanVO, MesGyInfoToPlanDTO.class);
            if (mesPlanXiaDaMapper.repeatPlan(mesGyInfoToPlanDTO) != 0) {
                return "选中项中有重复下达计划，下达失败";
            }
            mesGyInfoToPlanDTO.setFactoryId(factoryId);
            mesGyInfoToPlanDTO.setXiadauid(user);
            mesGyInfoToPlanDTO.setChecktime2(mesGyInfoToPlanDTO.getCheckTime2Date().format(dateTimeFormatter));
            log.debug("mesGyInfoToPlanDTO:{}",mesGyInfoToPlanDTO);
            mesPlanXiaDaMapper.planXiaDa1(mesGyInfoToPlanDTO, flag);
            mesPlanXiaDaMapper.planXiaDa2(mesGyInfoToPlanDTO);
            mesPlanXiaDaMapper.planXiaDa3(mesGyInfoToPlanDTO);
        }
        MesPlanXiadaJixingDO mesPlanXiadaJixingDO = MesPlanXiadaJixingDO.builder()
                .jixing(CommonUtils.stringNull(test.getJx()))
                .nianyue(CommonUtils.stringNull(test.getCheckTime2Date().format(DateTimeFormatter.ofPattern("yyyy-MM"))))
                .factoryId(factoryId)
                .build();
        if (mesPlanXiadaJixingMapper.repeatJX(mesPlanXiadaJixingDO) == 0) {
            mesPlanXiadaJixingMapper.insertJX(mesPlanXiadaJixingDO);
        }
        return "下达成功";
    }

    @Override
    public int xiaDaForJx(MesGyInfoToPlanDTO mesGyInfoToPlanDTO) {
        String flag;
        if (mesPlanXiaDaMapper.judgeFlag(mesGyInfoToPlanDTO) == 0) {
            flag = "";
        } else {
            flag = "新增";
        }
        String pattern;
        if (mesGyInfoToPlanDTO.getFactoryId().equals("16")) {
            pattern = "yyyy-MM-dd";
        } else {
            pattern = "yyyy-MM";
        }
        System.out.println(pattern);
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(pattern);
        mesGyInfoToPlanDTO.setChecktime2(mesGyInfoToPlanDTO.getCheckTime2Date().format(dateTimeFormatter));
        log.debug("mesGyInfoToPlanDTO:{}",mesGyInfoToPlanDTO);
        int count = mesPlanXiaDaMapper.xiaDaForJx(mesGyInfoToPlanDTO, flag);
        mesPlanXiaDaMapper.xiaDaForJx2(mesGyInfoToPlanDTO);
        MesPlanXiadaJixingDO mesPlanXiadaJixingDO = MesPlanXiadaJixingDO.builder()
                .jixing(CommonUtils.stringNull(mesGyInfoToPlanDTO.getJx()))
                .nianyue(CommonUtils.stringNull(mesGyInfoToPlanDTO.getCheckTime2Date().format(DateTimeFormatter.ofPattern("yyyy-MM"))))
                .factoryId(CommonUtils.stringNull(mesGyInfoToPlanDTO.getFactoryId()))
                .build();
        if (mesPlanXiadaJixingMapper.repeatJX(mesPlanXiadaJixingDO) == 0) {
            mesPlanXiadaJixingMapper.insertJX(mesPlanXiadaJixingDO);
        }
        return count;
    }

    //@Override
    //@Transactional(rollbackFor = Exception.class)
    //public String planXiaDa(String[] planIds, String factoryId, String user){
    //    String flag;
    //    //String state;
    //    if (mesPlanXiaDaMapper.judgeFlag() == 0) {
    //        flag = "";
    //    } else {
    //        flag = "新增";
    //    }
    //    int i;
    //    for (i = 0; i < planIds.length; i++){
    //        String planId = planIds[i];
    //        if (mesPlanXiaDaMapper.repeatPlan(planId) != 0) {
    //            return "选中项中有重复下达计划，下达失败";
    //        }
    //        mesPlanXiaDaMapper.planXiaDa1(planId);
    //        mesPlanXiaDaMapper.planXiaDa2(factoryId, user, flag, planId);
    //    }
    //    if (i == planIds.length) {
    //        return "下达成功";
    //    } else {
    //        return "下达失败，请重试";
    //    }
    //}

    @Override
    public int updateCheckTime(MesGyInfoToPlanDTO mesGyInfoToPlanDTO) {
        return mesGyInfoMapper.updateCheckTime(mesGyInfoToPlanDTO);
    }

}
